import React, {useState} from "react";
import {Keyboard, StyleProp, StyleSheet, TextInput, TextStyle, ViewStyle} from "react-native";
import {Input, InputProps} from "@rn-vui/themed";
import Animated, {useSharedValue, useAnimatedStyle, withTiming} from "react-native-reanimated";

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white'
    },
    input: {
        borderWidth: StyleSheet.hairlineWidth,
        borderColor: 'gray',
        borderRadius: 5,
        fontSize: 16,
        height: 44,
        paddingHorizontal: 10
    }
});

export type KeyboardInputProps = {
    style?: StyleProp<ViewStyle>;
    inputStyle?: StyleProp<TextStyle>;
} & InputProps;
const KeyboardInput = (props: KeyboardInputProps) => {
    const {style, inputStyle, ...rest} = props;
    const [keyboardShow, setKeyboardShow] = useState<boolean>(false);
    const translateY = useSharedValue(0);

    const animateStyle = useAnimatedStyle(() => ({
        transform: [{translateY: -translateY.value}]
    }));

    const viewStyle = React.useCallback(() => {
        if (keyboardShow) {
            return {
                position: 'fixed',
                left: 0,
                right: 0,
                bottom: 0,
                zIndex: 100,
            }
        } else {
            return {}
        }
    }, [keyboardShow])

    React.useEffect(() => {
        Keyboard.addListener('keyboardWillShow', (e) => {
            setKeyboardShow(true);
            translateY.value = withTiming(e.endCoordinates.height, {duration: e.duration});
        });

        Keyboard.addListener('keyboardWillHide', (e) => {
            translateY.value = withTiming(0, {duration: e.duration});
        });

        Keyboard.addListener('keyboardDidHide', (e) => {
            setKeyboardShow(false);
        });
    }, []);

    return (
        <Animated.View
            style={[
                styles.container,
                animateStyle,
                style,
            ]}
        >
            <TextInput style={[styles.input, inputStyle]} {...rest}/>
        </Animated.View>
    );
};

export default React.memo(KeyboardInput);
